package org.way.base.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.ContentType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class CommonFileUtil {

    private static final String DOT = ".";

    private static final String ZIP = ".zip";

    public static String readBase64() throws IOException {
        FileInputStream inputStream = null;
        try {
            // 读取文件
            File base64File = new File("C:\\Untitled1.txt");
            inputStream = new FileInputStream(base64File);
            int size = inputStream.available();
            byte[] bytes = new byte[size];
            int read = inputStream.read(bytes);

            // 转成char数组
            char[] chars = new char[size];
            for (int i = 0; i < size; i++) {
                chars[i] = (char) bytes[i];
            }

            return String.valueOf(chars);
        } catch (IOException ignored) {
            throw new IOException("读取文件失败");
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    public static MultipartFile toMultipartFile(File file) {
        MultipartFile multipartFile;
        try {
            DiskFileItem fileItem2 = (DiskFileItem) new DiskFileItemFactory()
                    .createItem("file",
                            ContentType.MULTIPART.getValue(),
                            true,
                            file.getName());
            Files.copy(Paths.get(file.getAbsolutePath()), fileItem2.getOutputStream());
            multipartFile = new CommonsMultipartFile(fileItem2);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return multipartFile;
    }

    public static void downloadZip(String zipName, List<File> fileList) {

        String userAgent = ServletUtils.getRequest().getHeader("user-agent").toLowerCase();
        HttpServletResponse response = ServletUtils.getResponse();

        ZipOutputStream zipOutputStream = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;

        try {
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                zipName = URLEncoder.encode(zipName, "UTF-8");
            } else {
                zipName = new String(zipName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + zipName);

            outputStream = response.getOutputStream();
            zipOutputStream = new ZipOutputStream(outputStream);

            for (File file : fileList) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buf = new byte[1024];
                int len;
                fileInputStream = new FileInputStream(file);
                while ((len = fileInputStream.read(buf)) != -1) {
                    zipOutputStream.write(buf, 0, len);
                    zipOutputStream.flush();
                }
            }
            zipOutputStream.flush();
            zipOutputStream.close();

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("导出zip文件失败");
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (zipOutputStream != null) {
                    zipOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    public static void zipExportFile() {
        ZipOutputStream zipOut = null;
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            List<File> fileList = Arrays.asList(
                    new File("D:\\2024-06-20\\1718861912815.docx"),
                    new File("D:\\2024-06-20\\1718861913032.docx"));

            for (File file : fileList) {
                fos = new FileOutputStream("D:\\2024-06-20\\2024-06-20.zip");
                zipOut = new ZipOutputStream(fos);
                fis = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOut.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zipOut.write(bytes, 0, length);
                    zipOut.flush();
                }
            }
            zipOut.flush();
            zipOut.close();
            fis.close();
            fos.close();
        } catch (Exception ignored) {

        }
    }

    private static void deleteFile(String fileStr) {
        File file = new File(fileStr);
        if (file.exists()) {
            if (file.delete()) {
                log.info("{} deleted successfully.", file);
            } else {
                log.info("{} deletion unSuccessfull.", file);
            }
        }
    }
}
